<?php
/**
 * 用户文件
 *
 * @author lwb
 */

namespace app\wechat\controller;

use app\wechat\controller\Dict;
use Custom\Constant;
use think\Log;

class Users extends Common {

    //dev开发环境
    protected $env = APP_ENV;

    public function __construct() {
        parent::__construct();
        $this->config = config('oss_url.' . $this->env);
    }
    
    /*
     * 我的资料信息
     */
    public function infoStatus($params){
        $result = $this->getWS('ucenter', 'users@infoStatus', ['u_code' => $this->uid]);
        
        if ($result['status'] != '2000') {
            return $this->parse_data(['code' => 5000, 'msg' => '获取信息失败']);
        }
        
        return $this->parse_data(['data' => $result['result']]);
    }

    /**
     * 用户基本信息
     * @Author   shangguoqing
     * @Email    guoqing.shang@mayi121.com
     * @DateTime 2017-08-22T15:11:12+0800
     * @param    string
     */
    public function userInfo($params) {
        $infoType = !empty($params['infoType'])?$params['infoType']:'0';
        $result = $this->getWS('ucenter', 'users@userInfo', ['u_code' =>  $this->uid]);
        if ($result['status'] != '2000') {
            return $this->parse_data(['code' => 5000, 'msg' => '获取信息失败']);
        }
        $result['result']['u_marriage_name'] = config('dict.marriage')[$result['result']['u_marriage']];
        $result['result']['u_edu_degree_name'] = config('dict.edu_degree')[$result['result']['u_edu_degree']];
        if($infoType == '1'){
            $userInfo = $result['result'];
            unset($result['result']);
            //资料信息
            $daturm = $this->getWS('ucenter', 'daturm@userDaturm', ['u_code' => $this->uid, 'fileType' => '1,2,3,10']);
            if (!empty($daturm['result'])) {
                foreach ($daturm['result'] as &$val) {
                    if ($val['is_local'] == '2') {
                        $val['url'] = config('view_upload_url') . '/' . $val['ud_url'];
                    } elseif ($val['is_local'] == '1') {
                        $val['url'] = config('ONLINE_SITES') . '/' . $val['ud_url'];
                    }
                }
            }
            //资料信息
            $result['result']['daturm'] = $daturm['result'];
            $result['result']['userInfo'] = $userInfo;
        }

        return $this->parse_data(['data' => $result['result']]);
    }

    /**
     * 获取城市联动
     * @Author   shangguoqing
     * @Email    guoqing.shang@mayi121.com
     * @DateTime 2017-08-23T11:40:59+0800
     * @param    [type]
     * @return   [type]
     */
    public function getCity($params) {
        if( empty($params['id']) ){
            return $this->parse_data(['data' => Dict::provinceList()]);
        }
        return $this->parse_data(['data' => Dict::cityList($params['id'])]);
    }
    /**
     * 获取银行省市区
     * @Author   shangguoqing
     * @Email    guoqing.shang@mayi121.com
     * @DateTime 2017-09-04T17:58:50+0800
     * @param    string
     */
    public function getBankCity($params){
       if(empty($params['type']) || $params['type']=='1' || empty($params['id'])){
            //银行省
            return $this->parse_data(['data' => Dict::BankProvince()]);
       }
       elseif($params['type'] == '2'){
            //银行市
            return $this->parse_data(['data' => Dict::BankCity($params['id'])]);

       }elseif($params['type'] == '3'){
            //银行区
            return $this->parse_data(['data' => Dict::BankArea($params['id'])]);
       }
    }
    
    /**
     * 保存用户实名信息
     * @Author   shangguoqing
     * @Email    guoqing.shang@mayi121.com
     * @DateTime 2017-08-22T16:15:03+0800
     * @param    [type]
     * @return   [type]
     */
    public function doIdCard($params) {
        $data = [
            'realName' => $params['u_true_name'],
            'phone' => session('username'),
            'identNo' => $params['u_ident_no'],
            'u_code' => $this->uid
        ];
        $result = $this->getWS('ucenter', 'users@userAuth', $data);
        if($result['status'] != '2000'){
            return $this->parse_data(['code' => 5000, 'msg' => $result['msg']]);
        }
        
        return $this->parse_data();
    }

    /**
     * 保存用户基本信息
     * @Author   shangguoqing
     * @Email    guoqing.shang@mayi121.com
     * @DateTime 2017-08-22T16:15:03+0800
     * @param    [type]
     * @return   [type]
     */
    public function douserInfo($params) {
        $params['u_code'] = $this->uid;
        $result = $this->getWS('ucenter', 'users@saveUserInfo', $params);
        if ($result['status'] != '2000') {
            return $this->parse_data(['code' => 5000, 'msg' => '保存信息失败']);
        }
        return $this->parse_data();
    }

    /**
     * 联系人
     * @Author   shangguoqing
     * @Email    guoqing.shang@mayi121.com
     * @DateTime 2017-08-22T12:20:49+0800
     * @return   [type]
     */
    public function contact($params) {
        $result = $this->getWS('ucenter', 'users@relationInfo', ['u_code' => $this->uid]);
        if ($result['status'] != '2000') {
            return $this->parse_data(['code' => 5000, 'msg' => '获取联系人信息失败']);
        }
        return $this->parse_data(['data' => $result['result']]);
    }

    /**
     * 联系人保存
     * @Author   shangguoqing
     * @Email    guoqing.shang@mayi121.com
     * @DateTime 2017-08-22T12:22:42+0800
     * @return   [type]
     */
    public function doContact($params) {
        $data = $params['relations'];
        foreach ($data as $key => $val) {
            if($val['phone'] == session('username')){
                return $this->parse_data(['code' => 5000, 'msg' => '联系人电话不能填自己电话']);
            }
            if (empty($val['name']) || empty($val['phone'])) {
                unset($data[$key]);
            }

            //————————————————————————————————————————————————————————————————-————————————
//            * 响应状态值说明：
//            *  200000	请求成功
//            *  400001	参数校验异常(请检查参数);400101	商户信息不存在
//            *  400102	商户IP地址不合法;400200	黑名单列表;400201	手机号码不能为空;400901	账户信息不存在
//            *  400902	应用类型信息不存在;403000	用户校验失败(请联系客服);403101	账户被系统禁用;
//            *  403102	账户未激活;500000 系统异常;500002  数据处理异常;500003  业务操作失败;
//            *  500004 远程调用失败;500005 账户余额异常;500006  请求外部系统失败;500901  邮箱未设置;
//            *  500902 账户信息已存在;500903 账户相关能力已激活;504000  系统超时;510101  用户产品可用数量不足

            //验证一小时3次。
            $checkData = array(
                'u_code'=>  $this->uid,
                'u_name'=>  $val['name'],
                'u_phone'=> $val['phone'],
            );
            //查询空号检测次数
            $checknum = $this->getWS('ucenter', 'users@userChecknumInfo', ['u_code' => $this->uid, 'u_from' => 1, 'u_type' => 1]);

            $numCount = count($checknum['result']);

            $num = 4;
            $remaining = $num - $numCount;

            if($numCount >= 5){
                return $this->parse_data(['code' => 5000, 'msg' => '校验次数超限,请于1小时后再试']);
            }else{

                if($remaining <= '0'){
                    $ck = '校验次数超限,请于1小时后再试';
                }else{
                    $ck = '你还可以输入'.$remaining.'次';
                }

                //验证空号检测
                $checkMobile = $this->getWS('channel', 'MobileCheck@checkMobile', ['mobiles'=>$val['phone']]);

                if($checkMobile['status'] != '2000'){
                    if($checkMobile['status'] != '510101'){
                        return $this->parse_data(['code' => 5000, 'msg' => '检测失败,请稍后！']);
                    }else{
                        //如果第一个供应商服务不可用，走第二个供应商入口验证

                    }
                }else{
                    $checkData['u_status'] = $checkMobile['result']['status'];
                    //status 0:空号；1:实号；2:停机；3:库无；4:沉默号；5:风险号；
                    if($checkMobile['result']['status'] == '0'){
                        //如果验证错误，记录一次错误。
                        $this->getWS('ucenter', 'users@saveChecknumInfo', $checkData);
                        return $this->parse_data(['code' => 5000, 'msg' => $val['name'].'信息有误！'.$ck]);
                    }else if($checkMobile['result']['status'] == '2'){
                        $this->getWS('ucenter', 'users@saveChecknumInfo', $checkData);
                        return $this->parse_data(['code' => 5000, 'msg' => $val['name'].'号码已停机！'.$ck]);
                    }else if($checkMobile['result']['status'] == '3'){
//                        $this->getWS('ucenter', 'users@saveChecknumInfo', $checkData);
//                        return $this->parse_data(['code' => 5000, 'msg' => $val['name'].'信息不可用！'.$ck]);
                    }else if($checkMobile['result']['status'] == '4'){
                        //验证实时检测
//                        $this->realTime($checkData);
//                        $this->getWS('ucenter', 'users@saveChecknumInfo', $checkData);
//                        return $this->parse_data(['code' => 5000, 'msg' => $val['name'].'号码不可用！'.$ck]);
                    }

                }

            }
            //————————————————————————————————————————————————————————————————-————————————

            $arr[] = $val['relation'];
        }

        if( !in_array('父亲',$arr) && !in_array('母亲',$arr) ){
            //return $this->parse_data(['code' => 5000, 'msg' => '至少选择父母中一方']);
        }
        $condition['relations'] = $data;
        $condition['u_code']=$this->uid;
        $count = count($data);
        if ($count < 2) {
            return $this->parse_data(['code' => 5000, 'msg' => '联系人至少填两个']);
        }
        $result = $this->getWS('ucenter', 'users@saveRelationInfo', $condition);
        if ($result['status'] != '2000') {
            return $this->parse_data(['code' => 5000, 'msg' => '保存联系人失败']);
        }
        return $this->parse_data();
    }

    /*
     * 验证实时检测
     *
     * */
    public function realTime($params){

        $checkTime = $this->getWS('channel', 'MobileCheck@checkTimeMobile', ['mobiles'=>$params['phone']]);
        if($checkTime['status'] != '2000'){
            //如果验证错误，记录一次错误。
            $this->getWS('ucenter', 'users@saveChecknumInfo', $params);
            return $this->parse_data(['code' => 5000, 'msg' => $params['name'].'号码不可用！']);
        }else{

            // 实时检测状态码返回说明：
            // numberType为1时:status 号码状态:1(正常)2(停机)
            // numberType为2时:status 号码状态:1(未启用)2(正常)3(欠费停机)
            // numberType为3时:status 号码状态:0(在网状态正常)1(在网状态停机)

            if($checkTime['numberType'] == '1'){
                if($checkTime['result']['status'] != '1'){
                    //如果验证错误，记录一次错误。
                    $this->getWS('ucenter', 'users@saveChecknumInfo', $params);
                    return $this->parse_data(['code' => 5000, 'msg' => $params['name'].'号码不可用！']);
                }
            }else if($checkTime['numberType'] == '2'){
                if($checkTime['result']['status'] != '2'){
                    //如果验证错误，记录一次错误。
                    $this->getWS('ucenter', 'users@saveChecknumInfo', $params);
                    return $this->parse_data(['code' => 5000, 'msg' => $params['name'].'号码不可用！']);
                }
            }else if($checkTime['numberType'] == '3'){
                if($checkTime['result']['status'] != '0'){
                    //如果验证错误，记录一次错误。
                    $this->getWS('ucenter', 'users@saveChecknumInfo', $params);
                    return $this->parse_data(['code' => 5000, 'msg' => $params['name'].'号码不可用！']);
                }
            }

        }

    }

    /*
     * 验证空号检查次数，超过3次一小时后再次验证
     *
     * */
    public function checknum($params){

        $data = array(
            'u_code'=>  $params['u_code'],
            'u_name'=>  $params['u_name'],
            'u_phone'=> $params['u_phone'],
        );

        //查询空号检测次数
        $checknum = $this->getWS('ucenter', 'users@userChecknumInfo', ['u_code' =>$params['u_code'], 'u_from' => 1, 'u_type' => 1]);

        $numCount = count($checknum['result']);
        if($numCount >= 3){
            return $this->parse_data(['code' => 5000, 'msg' => '校验次数超限,等1小时后在试']);
        }else{
            $this->getWS('ucenter', 'users@saveChecknumInfo', $data);
        }

    }


    /**
     * 更改绑定手机号
     * @Author   shangguoqing
     * @Email    guoqing.shang@mayi121.com
     * @DateTime 2017-08-22T16:31:27+0800
     * @param    string
     */
    public function updatePhone($params) {
        if (empty($params['code']) || (cookie($params['phone']) <> $params['code'])) {
            return $this->parse_data(['code' => 5000, 'msg' => '短信验证码不正确，请重新输入']);
        }

        $result = $this->getWS('ucenter', 'users@modifyPhone', ['u_code' => $this->uid, 'newUname' => $params['phone']]);
        if ($result['status'] != '2000') {
            return $this->parse_data(['code' => 5000, 'msg' => '保存失败']);
        }
        cookie($params['phone'], null);
        return $this->parse_data();
    }
    
    /**
     * 上传
     * @Author   shangguoqing
     * @Email    guoqing.shang@mayi121.com
     * @DateTime 2017-10-25T11:46:54+0800
     * @param    [type]
     * @return   [type]
     */
    public function userUpload($params) {
        $files = [];
        foreach ($params['daturmInfo'] as $k=>$v){
            $files[$k]['fileType'] = $v[0];
            $files[$k]['fileUrl'] = $v[1];
        }
        $data = [
            'files' => $files,
            'orderId' => $params['b_id']?:session('b_id'),
            'u_code' => $this->uid
        ];
        $result = $this->getWS('ucenter', 'daturm@upload', $data);
        if($result['status'] != '2000'){
            return $this->parse_data(['code' => 5000, 'msg' => $result['msg']]);
        }
        
        return $this->parse_data();
    }

    /**
     * 用户身份证照片
     * @Author   shangguoqing
     * @Email    guoqing.shang@mayi121.com
     * @DateTime 2017-08-23T12:11:37+0800
     * @param    [type]
     * @return   [type]
     */
    public function userIdCard($params) {
        $result = $this->getWS('ucenter', 'daturm@userDaturm', ['u_code' => $this->uid, 'fileType' => '1,2,3,10']);
        if ($result['status'] != '2000') {
            return $this->parse_data(['code' => 5000, 'msg' => '获取信息失败']);
        }

        foreach ($result['result'] as &$val) {
            $val['ud_name'] = config('dict.file_type')[$val['ud_type']];
            if($val['is_local'] == '2'){
                $val['ud_url'] = config('view_upload_url'). '/' . $val['ud_url'];
            }elseif($val['is_local'] == '1'){
                $val['ud_url'] = config('ONLINE_SITES'). '/' . $val['ud_url'];
            }
        }
        return $this->parse_data(['data' => $result['result']]);
    }
    /**
     * 合同照片
     * @Author   shangguoqing
     * @Email    guoqing.shang@mayi121.com
     * @DateTime 2017-09-11T16:03:55+0800
     * @param    [type]
     * @return   [type]
     */
    public function userContact($params) {
        $b_id = !empty($params['b_id']) ? $params['b_id'] : session('b_id');
        $result = $this->getWS('ucenter', 'daturm@userDaturm', ['u_code' => $this->uid,'orderId'=>$b_id]);
        if ($result['status'] != '2000') {
            return $this->parse_data(['code' => 5000, 'msg' => '获取信息失败']);
        }

        foreach ($result['result'] as &$val) {
            $val['ud_name'] = config('dict.file_type')[$val['ud_type']];
            if($val['is_local'] == '2'){
                $val['ud_url'] = config('view_upload_url'). '/' . $val['ud_url'];
            }elseif($val['is_local'] == '1'){
                $val['ud_url'] = config('ONLINE_SITES'). '/' . $val['ud_url'];
            }
        }
        return $this->parse_data(['data' => $result['result']]);
    }
    /**
     * 工作信息
     * @Author   shangguoqing
     * @Email    guoqing.shang@mayi121.com
     * @DateTime 2017-08-23T14:14:18+0800
     * @param    string
     */
    public function workInfo($params) {
        $result = $this->getWS('ucenter', 'work@workInfo', ['u_code' => $this->uid]);
        if ($result['status'] != '2000') {
            return $this->parse_data(['code' => 5000, 'msg' => '获取信息失败']);
        }
        $result['result']['school_date'] = date('Y-m-d', strtotime($result['result']['school_date']));
        $result['result']['com_typ_name'] = config('dict.com_type')[$result['result']['com_typ']];
        $result['result']['com_job_ttl_name'] = config('dict.job_ttl')[$result['result']['com_job_ttl']];
        $result['result']['indiv_crtfctn_name'] = config('dict.indiv_title')[$result['result']['indiv_crtfctn']];
        $result['result']['indiv_occ_name'] = config('dict.indiv_occ')[$result['result']['indiv_occ']];
            
        return $this->parse_data(['data' => $result['result']]);
    }

    /**
     * 保存工作信息
     * @Author   shangguoqing
     * @Email    guoqing.shang@mayi121.com
     * @DateTime 2017-08-23T14:14:18+0800
     * @param    string
     */
    public function doworkInfo($params) {
        $params['uw_fld'] = !empty($params['uw_fld'])?$params['uw_fld']:'6420';
        $params['uw_fld_name'] = !empty($params['uw_fld_name'])?$params['uw_fld_name']:'信息传输、软件和信息技术服务业->互联网和相关服务->互联网信息服务->互联网信息服务';
        $params['com_typ'] = !empty($params['com_typ'])?$params['com_typ']:'800';
        $params['com_job_ttl'] = !empty($params['com_job_ttl'])?$params['com_job_ttl']:'4';
        $params['indiv_crtfctn'] = !empty($params['indiv_crtfctn'])?$params['indiv_crtfctn']:'0';
        $params['indiv_occ'] = !empty($params['indiv_occ'])?$params['indiv_occ']:'Z';
        $params['cus_flag'] = !empty($params['school_date'])?'3':'2';
        $condition = $params;
        $condition['u_code'] = $this->uid;
        $result = $this->getWS('ucenter', 'work@saveInfo', $condition);
        if ($result['status'] != '2000') {
            return $this->parse_data(['code' => 5000, 'msg' => '保存失败']);
        }

        return $this->parse_data();
    }
    /**
     * 银行卡信息
     * @Author   shangguoqing
     * @Email    guoqing.shang@mayi121.com
     * @DateTime 2017-08-23T17:20:11+0800
     * @param    [type]
     * @return   [type]
     */
    public function bankCard($params){
        $result = $this->getWS('ucenter', 'bank@userBank', ['u_code'=>$this->uid]);
        if ($result['status'] != '2000') {
            return $this->parse_data(['code' => 5000, 'msg' => '获取信息失败']);
        }
        return $this->parse_data(['data'=>$result['result']]);
 
    }
    /**
     * 绑定银行卡
     * @Author   shangguoqing
     * @Email    guoqing.shang@mayi121.com
     * @DateTime 2017-08-31T16:54:36+0800
     * @param    [type]
     * @return   [type]
     */
    public function bindBank($params){
        $username = session('username');
        if(cookie('bank_'.$username) && cookie('bank_'.$username) >= 3){
            return $this->parse_data(['code' => 5000, 'msg' => '1小时内银行卡校验次数超限']);
        }
        if (empty($params['phone_code']) || (cookie($params['phone']) <> $params['phone_code'])) {
            return $this->parse_data(['code' => 5000, 'msg' => '短信验证码不正确，请重新输入']);
        }
        //获取银行卡名称
        $result = $this->getWS('channel', 'Pay@bankInfo', ['card_no'=>$params['card_no']]);

        if($result['status'] != '2000'){         
             return $this->parse_data(['code' => 5000, 'msg' => '获取银行卡信息失败']);
        }
        $info = $result['result'];
        if($info['ret_code'] != '0000'){
            return $this->parse_data(['code' => 5000, 'msg' => '您输入的卡号有误']);
        }
        if($info['card_type'] == '3'){
            return $this->parse_data(['code' => 5000, 'msg' => '不支持信用卡']);
        }
        if(empty(config('dict.bank_list')[$info['bank_code']])){
            return $this->parse_data(['code' => 5000, 'msg' => '不支持该银行卡']);
        }
        //查询用户姓名和身份证号
        $res  = $this->getWS('ucenter', 'users@userInfo', ['u_code' =>  $this->uid]);
        if($res['status'] != '2000'){         
             return $this->parse_data(['code' => 5000, 'msg' => '获取用户信息失败']);
        }
        //绑卡
        $condition['u_code']    = $this->uid;
        $condition['cardNo']    = $params['card_no'];
        $condition['realName']  = $res['result']['u_true_name'];
        $condition['identNo']   = $res['result']['u_ident_no'];
        $condition['phone']     = $params['phone'];
        $condition['bankName']  = $info['bank_name'];
        $condition['province']  = $params['province'];
        $condition['city']      = $params['city'];
        $condition['area']      = $params['area'];

        $res2 = $this->getWS('ucenter', 'bank@bankBind', $condition);
        $bank_num = cookie('bank_'.$username)?:0;
        cookie('bank_'.$username,$bank_num+1,3600);
        if($res2['status'] != '2000'){ 
            return $this->parse_data(['code' => 5000, 'msg' => '绑卡失败，银行卡号校验不一致']);
        }
        cookie('bank_'.$username,null);
        cookie($params['phone'],null);
        return $this->parse_data();
    }
    /**
     * 用户补充资料
     * @Author   shangguoqing
     * @Email    guoqing.shang@mayi121.com
     * @DateTime 2017-08-30T15:39:41+0800
     * @param    string
     */
    public function upUserInfo($params) {
        if(empty($params['b_id']) && $this->checkOrder()){
            return $this->parse_data(['code' => 5002, 'msg' => '非法操作']);
        }
        $b_id = !empty($params['b_id']) ? $params['b_id'] : session('b_id');
        $infoType = !empty($params['infoType'])?$params['infoType']:'0';
        $data = [];
        if(!empty($b_id)){
            //订单信息
            $order = $this->getWS('credit', 'apply@applyInfo', ['b_id' => $b_id]);

            session('fund_name', $order['result']['fund_name']);

            if ($order['status'] == '2000') {

                //计算x+y模式每月利息加服务费
                if($order['result']['p_partner_service'] == 1){
                    $service = round($order['result']['b_borrow_amount'] * ($order['result']['p_rate']/100)/$order['result']['p_period'],2);
                }else{
                    $service = round($order['result']['b_borrow_amount'] * ($order['result']['p_rate']/100)/$order['result']['p_period'] + $order['result']['p_service_price'],2);
                }

                //判断是不是x+y模式
                if($order['result']['p_return_type'] == 4){
                    //计算X的模式
                    $order['result']['x_month_pay'] = round($order['result']['b_borrow_amount'] * ($order['result']['p_x_proportion']/100)/$order['result']['p_x_month']+$service, 2);
                    //计算Y的模式
                    $order['result']['y_month_pay'] = round($order['result']['b_borrow_amount'] * ($order['result']['p_y_proportion']/100)/$order['result']['p_y_month']+$service, 2);
                }
                $order['result']['r_rent_type_name'] = $order['result']['r_rent_type'] == 1 ? '合租' : '整租';
                $order['result']['month_rent_amt'] = round($order['result']['b_borrow_amount'] / $order['result']['b_period'] + $service, 2);


                //判断 起始时间选择：1、月，2、日（月：指的是下月、推迟2月。日指的是1-28的某一日）
                if($order['result']['partner_repay_time'] == 2){
                    $order['result']['repayment_day'] = $order['result']['partner_repay_day'];
                }else{
                    $order['result']['repayment_day'] = $order['result']['repay_day']?$order['result']['repay_day']:min('28',date('d',strtotime("-".$order['result']['p_advance_return_day']." days",strtotime($order['result']['start_rent_date']))));
                }

                //判断用户每个月几号还款
//                if($order['result']['partner_repay_time'] == 2){
//                    $order['result']['repayment_day'] =  $order['result']['partner_repay_day'];
//                }else{
//                    $order['result']['repayment_day'] =   min('28',date('d',strtotime("-".$order['result']['p_advance_return_day']." days",strtotime($order['result']['start_rent_date']))));
//                }
            }
            $order['result']['is_update_order'] = session('order_price')?false:true;
            $data['orderInfo'] = $order['result'];
        }

        //用户信息
        $user = $this->getWS('ucenter', 'users@userInfo', ['u_code' => $this->uid, 'fundName' => $order['result']['fund_name']]);
        $user['result']['is_auth'] = $order['result']['fund_name'] == 'guoyu'?true:false;
        $user['result']['is_open'] = in_array($order['result']['fund_name'], ['mayi','freeloan'])?false:true;
        $user['result']['u_marriage_name'] = config('dict.marriage')[$user['result']['u_marriage']];
        $user['result']['u_edu_degree_name'] = config('dict.edu_degree')[$user['result']['u_edu_degree']];
        $data['userInfo'] = $user['result'];
        
        if($infoType == '1'){
            //资料信息
            $daturm = $this->getWS('ucenter', 'daturm@userDaturm', ['u_code' => $this->uid, 'orderId' => $b_id]);
            if (!empty($daturm['result'])) {
                foreach ($daturm['result'] as &$val) {
                    if ($val['is_local'] == '2') {
                        $val['ud_url'] = config('view_upload_url') . '/' . $val['ud_url'];
                    } elseif ($val['is_local'] == '1') {
                        $val['ud_url'] = config('ONLINE_SITES') . '/' . $val['ud_url'];
                    }
                }
            }
            //资料信息
            $data['daturm'] = $daturm['result'];
        } elseif ($infoType == '2'){
            //亲属信息
            $relation = $this->getWS('ucenter', 'users@relationInfo', ['u_code' => $this->uid]);
            $data['contact'] = $relation['result'];
            //工作信息
            $work = $this->getWS('ucenter', 'work@workInfo', ['u_code' => $this->uid]);
            $work['result']['com_typ_name'] = config('dict.com_type')[$work['result']['com_typ']];
            $work['result']['com_job_ttl_name'] = config('dict.job_ttl')[$work['result']['com_job_ttl']];
            $work['result']['indiv_crtfctn_name'] = config('dict.indiv_title')[$work['result']['indiv_crtfctn']];
            $work['result']['indiv_occ_name'] = config('dict.indiv_occ')[$work['result']['indiv_occ']];
            $data['workInfo'] = $work['result'];
            
            //资料信息
            $daturm = $this->getWS('ucenter', 'daturm@userDaturm', ['u_code' => $this->uid, 'orderId' => $b_id]);
            if (!empty($daturm['result'])) {
                foreach ($daturm['result'] as &$val) {
                    $val['ud_name'] = config('dict.file_type')[$val['ud_type']];
                    if ($val['is_local'] == '2') {
                        $val['url'] = config('view_upload_url') . '/' . $val['ud_url'];
                    } elseif ($val['is_local'] == '1') {
                        $val['url'] = config('ONLINE_SITES') . '/' . $val['ud_url'];
                    }
                }
            }
            //资料信息
            $data['daturm'] = $daturm['result'];
        } else if($infoType == '3') {
            $partner_conf = $order['result']['partner_conf']?$order['result']['partner_conf']:session('partner_conf');
            if(!$partner_conf){
                return $this->parse_data(['code' => 5000, 'msg' => '请先配置文件类型']);
            }
            $fileType = json_decode($partner_conf,true);
            $i=0;
            foreach ($fileType as $k=>$v){
                $daturmType[$i]['ud_type'] = $k;
                $daturmType[$i]['ud_num'] = $v;
                $daturmType[$i]['ud_name'] = config('dict.file_type')[$k];
                $i++;
            }
            $data['daturmType'] = $daturmType;
        } else if ($infoType == '4') {
            $hasInsurance = 0;
            $isPass = 0;
            $partnerOrder = $this->getWS('credit', 'PartnersOrder@partnerSelect', ['b_id' => $b_id, 'order_type' => ['neq','8']]);
            // 如果order查询成功，并且存在记录，查询保险信息
            if ($partnerOrder['status'] == Constant::SUCCESS_CODE && $partnerOrder['result']) {
                $orderNum = $partnerOrder['result'][0]['order_num'];
                $hasInsurance = 1;
                $partnerInsurance = $this->getWS('credit', 'Insurance@getInsuranceInfo', ['order_num' => $orderNum]);
                if ($partnerInsurance['result']) {
                    $partnerInsurance['result']['training_start_time'] = date('Y-m-d', strtotime($partnerInsurance['result']['training_start_time']));
                    $partnerInsurance['result']['training_end_time'] = date('Y-m-d', strtotime($partnerInsurance['result']['training_end_time']));
                }
                // 如果pre_insurance_status状态为1标识已经预投保过
                $isPass = $partnerInsurance['result']['pre_insurance_status'] == 1 ? 1 : 0;
                $data = $partnerInsurance['result'];
            }
            $data['hasInsurance'] = $hasInsurance;
            $data['isPass'] = $isPass;
        }

        return $this->parse_data(['data' => $data]);
    }

    /**
     * 用户返回补充资料
     * @Author   shangguoqing
     * @Email    guoqing.shang@mayi121.com
     * @DateTime 2017-08-30T15:39:41+0800
     * @param    string
     */
    public function backUserInfo($params) {
        $infoType = !empty($params['infoType'])?$params['infoType']:'0';
        $data = [];
        
        //用户信息
        $user = $this->getWS('ucenter', 'users@userInfo', ['u_code' => $this->uid]);
        $user['result']['u_marriage_name'] = config('dict.marriage')[$user['result']['u_marriage']];
        $user['result']['u_edu_degree_name'] = config('dict.edu_degree')[$user['result']['u_edu_degree']];
        $data['userInfo'] = $user['result'];
        
        //亲属信息
        $relation = $this->getWS('ucenter', 'users@relationInfo', ['u_code' => $this->uid]);
        $data['contact'] = $relation['result'];
        //工作信息
        $work = $this->getWS('ucenter', 'work@workInfo', ['u_code' => $this->uid]);
        $work['result']['com_typ_name'] = config('dict.com_type')[$work['result']['com_typ']];
        $work['result']['com_job_ttl_name'] = config('dict.job_ttl')[$work['result']['com_job_ttl']];
        $work['result']['indiv_crtfctn_name'] = config('dict.indiv_title')[$work['result']['indiv_crtfctn']];
        $work['result']['indiv_occ_name'] = config('dict.indiv_occ')[$work['result']['indiv_occ']];
        $data['workInfo'] = $work['result'];
        if($infoType == '1'){
            //订单信息
            $order = $this->getWS('credit', 'apply@applyInfo', ['b_id' => $params['b_id']]);
            $data['orderInfo'] = $order['result'];

            //资料信息
            // $daturm = $this->getWS('ucenter', 'daturm@userDaturm', ['u_code' => $this->uid, 'orderId' => $params['b_id'], 'fileType' => '1,2,3,10']);
            $daturm = $this->getWS('ucenter', 'daturm@userDaturm', ['u_code' => $this->uid, 'orderId' => $params['b_id'], 'fileType' => '1,2,3']);
            if (!empty($daturm['result'])) {
                foreach ($daturm['result'] as &$val) {
                    $val['ud_name'] = config('dict.file_type')[$val['ud_type']];
                    if ($val['is_local'] == '2') {
                        $val['url'] = config('view_upload_url') . '/' . $val['ud_url'];
                    } elseif ($val['is_local'] == '1') {
                        $val['url'] = config('ONLINE_SITES') . '/' . $val['ud_url'];
                    }
                }
            }
            $data['daturmInfo'] = $daturm['result'];
        }

        return $this->parse_data(['data' => $data]);
    }
    
    /**
     * 提交信息
     * @Author   shangguoqing
     * @Email    guoqing.shang@mayi121.com
     * @DateTime 2017-09-12T11:46:54+0800
     * @param    [type]
     * @return   [type]
     */
    public function submitMsg($params) {
        if(empty($params['b_id']) && $this->checkOrder()){
            return $this->parse_data(['code' => 5002, 'msg' => '非法操作']);
        }
        $b_id = !empty($params['b_id']) ? $params['b_id'] : session('b_id');
        //修改订单状态为审核中
        $result = $this->getWS('credit', 'Apply@updateApply', ['b_id' => $b_id, 'data' => ['b_status' => '1000','b_apply_time' => date('Y-m-d H:i:s')]]);
        if($result['status'] != '2000'){
            return $this->parse_data(['code' => 5000, 'msg' => '保存信息失败']);
        }
        if(session('partner_id')){
            $jump_url = '/order/jsubmitorder?id='.$b_id;
        }else{
            $jump_url = '/order/jsubmitorder?id='.$b_id;
        }
        return $this->parse_data(['data' => ['jumpUrl' => $jump_url]]);
    }  
    
    /*
     * 身份证图片检查
     */
    public function checkIdCard($params){

        //ocr人脸识别是否开启
        switch ($params['ocr_open_where']) {
            case 'apply_open': // 正常申请流程时ocr校验的配置
                $config_ocr_open = config('ocr.apply_open');
                break;
            case 'back_open': // 审核回退时ocr校验的配置
                $config_ocr_open = config('ocr.back_open');
                break;
            default:
                // 默认为正常申请流程时ocr校验的配置为主
                $config_ocr_open = config('ocr.apply_open');
        }

        if($config_ocr_open == 'on'){
            //通过b_id查询机构id
            $partner_id = db("borrow_apply")->field('partner_id')->where("b_id = '{$params['b_id']}'")->find();

            $checkOcrData = array(
                'u_code'     => $this->uid,
                'u_b_id'     => $params['b_id'],
                'partner_id' => $partner_id['partner_id'],
            );

            //查询是否需要ocr人脸校验
            $checkOcrResult = $this->checkOcrNum($checkOcrData);

        }else{
            return $this->parse_data(['code' => '3000', 'msg' => '', 'data' => '']);
        }


        //如果ocr人脸校验失败的次数超过了机构配置的次数（默认一次），则不进行二次校验
        if ($checkOcrResult['code'] == 2000) {
            if ($params['fileType'] == 1 || $params['fileType'] == 2) {//身份证正反面

                // 检测参数
                if (empty($params['fileType']) || empty($params['fileContent'])) {
                    return $this->parse_data(['code' => '5000', 'msg' => '参数传输错误']);
                }


                //验证ocr身份证信息
                $result = $this->getWS('channel', 'Auth@ocridcardAuth', ['idCardSide' => $params['fileType'], 'image' => $params['fileContent']]);

                Log::write($result, 'ocr身份证接口返回', true, 'ocrcard/');

                //之前的验证调用接口，不用了。
                // $result = $this->getWS('channel', 'linkface@checkIdCard', ['fileContent' => $params['fileContent'], 'fileType' => $params['fileType'], 'ext' => $params['ext']]);

                $u_desc = $result['result']['msg'].' '.$result['result']['reason'].'('.config('dict.file_type')[$params['fileType']].')';

                if ($result['status'] != '2000') {
                    $orcData = [
                        'u_code'   => $this->uid,
                        'u_b_id'   => $params['b_id'],
                        'u_from'   => 2,
                        'u_type'   => $params['fileType'] == 1 ? 3 : 4,
                        'u_name'   => $params['u_true_name'],
                        'u_status' => 6,
                        'u_desc'   => 'OCR人脸校验失败,'.$u_desc,
                    ];
                    $this->getWS('ucenter', 'users@saveChecknumInfo', $orcData);
                    return $this->parse_data(['code' => '5000', 'msg' => $u_desc, 'data' => ['last_pop' => $checkOcrResult['last_pop']]]);
                }
            } else if ($params['fileType'] == 3) {//手持身份证验证
                // 检测参数
                if (empty($params['u_ident_no']) || empty($params['u_true_name']) || empty($params['fileContent'])) {
                    return $this->parse_data(['code' => '5000', 'msg' => '参数错误']);
                }

                //上传的图片进行压缩
//                $ret = $this->getWS("channel", "upload@compressUpload", ['fileContent' => $params['fileContent']]);
//                $url = $this->config['jump_url'] . $ret['result']['url'];

                $data = [
                    'idCard' => $params['u_ident_no'],//身份证号码
                    'name'   => $params['u_true_name'],//姓名
                    'image'  => $params['fileContent'],// Base64，大小限制100k以内。支持PEG,JPG,PNG,BMP等格式，建议JPG效率高
                ];

                //调用手持身份证照片，验证人和身份证是否是同一个人。
                $result = $this->getWS('channel', 'Auth@faceRecognition', $data);
                Log::write($result, 'ocr人脸接口返回', true, 'ocrcard/');

                $u_desc = $result['result']['data']['msg'].' '.$result['result']['reason'].'('.config('dict.file_type')[$params['fileType']].')';

                if ($result['status'] != '2000' || ($result['status'] == '2000' && $result['result']['data']['score'] < config('ocr.score'))) {
                    $orcData = [
                        'u_code'   => $this->uid,
                        'u_b_id'   => $params['b_id'],
                        'u_from'   => 2,
                        'u_type'   => 5,
                        'u_name'   => $params['u_true_name'],
                        'u_status' => 6,
                        'u_desc'   => 'OCR人脸校验失败,'.$u_desc,
                    ];
                    $this->getWS('ucenter', 'users@saveChecknumInfo', $orcData);

                    return $this->parse_data(['code' => '5000', 'msg' => $u_desc, 'data' => ['last_pop' => $checkOcrResult['last_pop']]]);
                }
            } else {
                return $this->parse_data(['code' => '5000', 'msg' => '参数传输错误']);
            }
        } else {
            return $this->parse_data(['code' => '3000', 'msg' => $checkOcrResult['msg']]);
        }

        return $this->parse_data(['data' => $result['result']]);
    }


    /**
     * 上传资料及身份信息
     * @Author   lwb
     * @param    [type]
     * @return   [type]
     */
    public function authForm($params) {

        if($params['userInfo']['is_auth'] == '1'){
            $age = getAge($params['userInfo']['u_ident_no']);
            //获取商户配置
            $partnerInfo = $this->getWS('credit', 'partnersOrder@partnerInfo', ['partner_id'=>session('partner_id')]);

            if(!($age>=$partnerInfo['result']['partner_min_age'] && $age<=$partnerInfo['result']['partner_max_age'])){ //年龄范围
                return $this->parse_data(['code'=>'5000', 'msg'=>'年龄必须在'.$partnerInfo['result']['partner_min_age'].'周岁到'.$partnerInfo['result']['partner_max_age'].'周岁范围！']);
            }

            $data = [
                'realName' => $params['userInfo']['u_true_name'],
                'phone' => session('username'),
                'identNo' => $params['userInfo']['u_ident_no'],
                'u_code' => $this->uid
            ];
            $result = $this->getWS('ucenter', 'users@userAuth', $data);
            if($result['status'] != '2000'){
                return $this->parse_data(['code' => 5000, 'msg' => $result['msg']]);
            }
        }else{
            $faceInfo = $this->getWS('ucenter', 'users@faceInfo', ['u_code' => $this->uid]);
        }
        
        $files = [];
        foreach ($params['daturmInfo'] as $k=>$v){
            $files[$k]['fileType'] = $v[0];
            $files[$k]['fileUrl'] = $v[1];
        }
        $data = [
            'files' => $files,
            'orderId' => $result['result']['b_id'],
            'u_code' => $this->uid
        ];
        $result = $this->getWS('ucenter', 'daturm@upload', $data);
        if($result['status'] != '2000'){
            return $this->parse_data(['code' => 5000, 'msg' => $result['msg']]);
        }

        // 获取账单模式
        $partnerFundList = $this->getWS('credit', 'product@partnerFundList', ['partner_id'=>session('partner_id')]);

        if(count($partnerFundList['result']) == 1){
            // 1、蚂蚁账单,2、银行出资信贷,3、信用卡
            if($partnerFundList['result'][0]['fund_type'] == 1){
                $jump_url = '/user/addmsg';
            }else{
                //信用卡暂时注释
//                $jump_url = '/order/product_list';
            }
        }else{
            //修改流程跳转填写基本信息
            $jump_url = '/user/addmsg';
        }

        
        return $this->parse_data(['data' => ['jumpUrl' => $jump_url]]);
    }
    
    /**
     * 上传视频及对比
     * @Author   lwb
     * @param    [type]
     * @return   [type]
     */
    public function videoForm($params) {
        //用户信息
        $user = $this->getWS('ucenter', 'users@userInfo', ['u_code' => $this->uid]);
        $data = [
            'fileContent' => $params['content'],
            'motions' => $params['motions'],
            'realName' => $user['result']['u_true_name'],
            'identNo' => $user['result']['u_ident_no'],
            'ext' => $params['ext']
        ];
        $result = $this->getWS('channel', 'linkface@checkIdEntity', $data);
        if($result['status'] != '2000'){
            return $this->parse_data(['code' => 5000, 'msg' => $result['msg']]);
        }
        
        $linkFace = $this->getWS('ucenter', 'users@updateLinkFace', ['u_code' => $this->uid]);
        if($linkFace['status'] != '2000'){
            return $this->parse_data(['code' => 5000, 'msg' => '人脸识别失败']);
        }
        
        if(session('order_price')){
            $jump_url = '/user/orderform?order_price='.session('order_price');
        }else{
            $jump_url = '/user/orderform';
        }
        
        return $this->parse_data(['data' => ['jumpUrl' => $jump_url]]);
    }
    
    /**
     * 通话记录
     * @Author   lwb
     * @param    [type]
     * @return   [type]
     */
    public function acquireYys($params) {
        if($params['task_stage'] == 'INIT'){
            //用户信息
            $user = $this->getWS('ucenter', 'users@userInfo', ['u_code' => $this->uid]);
            $data = [
                'u_code' => $this->uid,
                'u_true_name' => $user['result']['u_true_name'],
                'u_ident_no' => $user['result']['u_ident_no'],
                'u_name' => session('username')
            ];
            $result = $this->getWS('channel', 'yysdata@createTask', $data);
            if($result['status'] != '2000'){
                return $this->parse_data(['code' => 5000, 'msg' => $result['msg']]);
            }
            $task_id = $result['result']['task_id'];
        }else{
            $task_id = $params['task_id'];
        }
        
        $data = [
            'task_id' => $task_id,
            'task_stage' => $params['task_stage'],
        ];
        if($params['task_stage'] == 'INIT'){
            $data['u_name'] = session('username');
            $data['user_pass'] = $params['user_pass'];
        }else{
            if(!empty($params['sms_code'])){
                $data['sms_code'] = $params['sms_code'];
            }
            if(session('auth_code')){
                $data['auth_code'] = session('auth_code');
            }
        }
        $result = $this->getWS('channel', 'yysdata@acquireYys', $data);
        if($result['status'] == '2001'){
            if($result['result']['code'] == '101' || $result['result']['code'] == '123'){
                session('auth_code', $result['result']['auth_code']);
            }
            $jump_url = '/user/addsms?task_id='.$task_id.'&task_stage='.$result['result']['next_stage'];
        }else{
            if($result['status'] != '2000'){
                return $this->parse_data(['code' => 5000, 'msg' => $result['msg']]);
            }
            $yys = $this->getWS('ucenter', 'users@addYys', [
                'u_code' => $this->uid,
                'task_id' => $task_id,
            ]);
            if($yys['status'] != '2000'){
                return $this->parse_data(['code' => 5000, 'msg' => $yys['msg']]);
            }
            $jump_url = '/user/addmsg';
        }
        
        return $this->parse_data(['code' => 2000, 'data' => ['jumpUrl' => $jump_url]]);
    }
    
    /*
     * 发送验证码
     */
    public function sendcode($params) {
        $code = rand(1000, 9999);
        $result = $this->getWS('channel', 'message@send', ['tplName' => 'R001', 'phone' => $params['phone'], 'param' => ['code' => $code]]);
        if ($result['status'] != '2000') {
            return $this->parse_data(['code' => 5000, 'msg' => '发送失败']);
        }
        
        cookie($params['phone'], $code, '300');
        return $this->parse_data();
    }
    
    /*
     * 发送验证码
     */
    public function sendSmsCode($params) {
        $result = $this->getWS('channel', 'yysdata@sendCode', ['task_id' => $params['task_id']]);
        if ($result['status'] != '2000') {
            return $this->parse_data(['code' => 5000, 'msg' => '发送失败']);
        }
        
        return $this->parse_data(['code' => 2000, 'msg' => '发送成功']);
    }

    /**
     * 协议付-预绑卡
     */
    public function preBindCard($params)
    {
        // 预绑卡模拟参数
        // $params = array(
        //         'bankCartNo' => '6228480444455553333', // 银行卡号
        //         'phone' => '18689262777' // 手机号
        //     );

        // 检测参数
        if(empty($params['bankCartNo']) || empty($params['phone'])){
            return $this->parse_data(['code'=>'5000', 'msg'=>'参数传输错误']);
        }

        // 查询用户姓名和身份证号
        $userInfo  = $this->getWS('ucenter', 'users@userInfo', ['u_code'=>$this->uid]);
        if($userInfo['status'] != '2000'){         
            return $this->parse_data(['code'=>'5000', 'msg'=>'获取用户信息失败']);
        }

        // 预绑卡
        $params['u_code'] = $this->uid; // 用户code
        $params['userName'] = $userInfo['result']['u_true_name']; // 姓名
        $params['idNo'] = $userInfo['result']['u_ident_no']; // 身份证号
        $preBindCard = $this->getWS('channel', 'Agreementpay@preBindCard', $params);
        if($preBindCard['status'] != '2000'){         
            return $this->parse_data(['code'=>'5000', 'msg'=>$preBindCard['msg']]);
        }

        return $this->parse_data(['code'=>'2000', 'msg'=>'请求成功', 'data'=>$preBindCard['result']]);
    }

    /**
     * 协议付-确认绑卡（携带短信验证码绑卡）
     */
    public function confirmBindCard($params)
    {
        // // 模拟参数
        // $params = array(
        //         'uniqueCode' => '201812201027303062863', // 预签约唯一码
        //         'phoneCode' => '123456', // 短信验证码
        //         'bankCartNo' => '6228480444455553333', // 银行卡号
        //         'phone' => '18689262777' // 手机号
        //     );

        // 参数校验
        if(empty($params['uniqueCode']) || empty($params['phoneCode']) || empty($params['bankCartNo']) || empty($params['phone'])){
            return $this->parse_data(['code'=>'5000', 'msg'=>'参数传输错误']);
        }

        //获取银行卡名称
//        $bankInfo = $this->getWS('channel', 'Pay@bankInfo', ['card_no'=>$params['bankCartNo']]);
//        if($bankInfo['status'] != '2000'){
//            return $this->parse_data(['code'=>'5000', 'msg'=>'获取银行卡信息失败']);
//        }
//        if($bankInfo['result']['ret_code'] != '0000'){
//            return $this->parse_data(['code'=>'5000', 'msg'=>'您输入的卡号有误']);
//        }
//        if($bankInfo['result']['card_type'] == '3'){
//            return $this->parse_data(['code'=>'5000', 'msg'=>'不支持信用卡']);
//        }
//        if(empty(config('dict.bank_list')[$bankInfo['result']['bank_code']])){
//            return $this->parse_data(['code'=>'5000', 'msg'=>'不支持该银行卡']);
//        }

        //查询用户姓名和身份证号
        $userInfo  = $this->getWS('ucenter', 'users@userInfo', ['u_code'=>$this->uid]);
        if($userInfo['status'] != '2000'){         
            return $this->parse_data(['code'=>'5000', 'msg'=>'获取用户信息失败']);
        }

        // 确认绑卡
        $confirmBindCard = $this->getWS('channel', 'Agreementpay@confirmBindCard', ['uniqueCode'=>$params['uniqueCode'], 'phoneCode'=>$params['phoneCode']]);
        if($confirmBindCard['status'] != '2000'){         
            return $this->parse_data(['code'=>'5000', 'msg'=>$confirmBindCard['msg']]);
        }
        // Log::write($confirmBindCard, '确认绑卡接口返回', true, 'confirmBindCard/');

        // 用户银行卡信息添加
        $condition['u_code']    = $this->uid;
        $condition['cardNo']    = $params['bankCartNo'];
        $condition['realName']  = $userInfo['result']['u_true_name'];
        $condition['identNo']   = $userInfo['result']['u_ident_no'];
        $condition['phone']     = $params['phone'];
        $condition['bankName']  = $confirmBindCard['result']['bank_name'];
        $condition['protocolNo']  = $confirmBindCard['result']['protocol_no'];
        // $condition['province']  = $params['province'];
        // $condition['city']      = $params['city'];
        // $condition['area']      = $params['area'];
        $userBankBind = $this->getWS('ucenter', 'bank@userBankBind', $condition);
        if($userBankBind['status'] != '2000'){ 
            return $this->parse_data(['code'=>'5000', 'msg'=>'绑卡失败']);
        }
        // Log::write($userBankBind, '用户银行卡信息添加', true, 'confirmBindCard/');

        return $this->parse_data(['code'=>'2000', 'msg'=>'请求成功', 'data'=>$confirmBindCard['result']]);
    }


    /**
     * 保险-签到功能
     */
    public function sign()
    {
        if(!empty($_POST)){
            $request = request();
            $params = $request->param();
            $datas = json_decode($params['datas'],true);

            //获取保险信息
            $insuranceInfo = $this->getWS('credit', 'Insurance@getInsuranceInfo', ['u_code'=>$this->uid,'pre_insurance_status'=>1,'training_start_time'=>['lt',date('Y-m-d H:i:s',time())],'training_end_time'=>['gt',date('Y-m-d H:i:s',time())],'is_delete'=>2]);

            // 添加打卡记录
            $condition['u_code']    = $this->uid;
            $condition['partner_id']    = $insuranceInfo['result']['partner_id'];
            $condition['product_id']    = $insuranceInfo['result']['p_id'];
            $condition['sign_date']    = date('Y-m-d',$datas['sign_time']);

            //查看是否存在打卡记录
            $signInfo = $this->getWS('ucenter', 'users@getSignData', $condition);
            if(empty($signInfo['result'])){
                return $this->parse_data(['code'=>'5000', 'msg'=>'今天不是上课日']);
            }

            $condition['sign_time']    = $datas['sign_time'];

            //补卡只能补本周
            if($this->getSameWeek(time(),$condition['sign_time'])){
                $res = $this->getWS('ucenter', 'users@saveSignData', $condition);
                if($res['status'] != '2000'){
                    return $this->parse_data(['code'=>'5000', 'msg'=>$res['msg']]);
                }
                return $this->parse_data(['code'=>'2000', 'msg'=>'请求成功']);
            }else{
                return $this->parse_data(['code'=>'5000', 'msg'=>'限补本周缺卡']);
            }
        }else{
            return view('user/sign');
        }
    }


    function getSameWeek($pretime,$aftertime){
        $flag = false;//默认不是同一周
        $afweek = date('w',$aftertime);//当前是星期几
        $mintime = $aftertime - $afweek * 3600*24;//一周开始时间
        $maxtime = $aftertime + (7-$afweek)*3600*24;//一周结束时间
        if ( $pretime >= $mintime && $pretime <= $maxtime){//同一周
            $flag = true;
        }
        return $flag;
    }

    /**
     * 获取签到数据
     */
    public function getSignData(){

        //获取保险信息
        $insuranceInfo = $this->getWS('credit', 'Insurance@getInsuranceInfo', ['u_code'=>$this->uid,'pre_insurance_status'=>1,'training_start_time'=>['lt',date('Y-m-d H:i:s',time())],'training_end_time'=>['gt',date('Y-m-d H:i:s',time())],'is_delete'=>2]);

        // 获取用户code
        $condition['u_code']    = $this->uid;
        $condition['partner_id']    = $insuranceInfo['result']['partner_id'];
        $condition['product_id']    = $insuranceInfo['result']['p_id'];

        $data = $this->getWS('ucenter', 'users@getSignData', $condition);
        //已打卡日期
        $my_day = [];
        $q_day = [];
        $w_day = [];
        foreach ($data['result'] as $k=>$v){
            if($v['status'] == 1){
                array_push($my_day,$v['sign_time']);
            }else if($v['status'] == 0 && strtotime($v['sign_date']) < time() && $v['sign_date'] != date('Y-m-d',time())){
                array_push($q_day,strtotime($v['sign_date']));
            }else{
                array_push($w_day,strtotime($v['sign_date']));
            }
        }
        return $this->parse_data(['code'=>'2000', 'msg'=>'请求成功','data'=>['my_day'=>$my_day,'q_day'=>$q_day,'w_day'=>$w_day]]);
    }

    /**
     * 保存投保课程信息
     * @param $params
     */
    public function saveInsuranceInfo($params) {
        // 获取订单信息
        $bid = !empty($params['b_id']) ? $params['b_id'] : session('b_id');
        Log::write($bid, '订单查询参数', true, 'insurance/');
        $partnerOrder = $this->getWS('credit', 'PartnersOrder@partnerSelect', ['b_id' => $bid, 'order_type' => ['neq','8']]);
        Log::write($partnerOrder, '订单查询结果', true, 'insurance/');
        $orderInfo = $partnerOrder['result'][0];

        // 获取用户信息
        $user = $this->getWS('ucenter', 'users@userInfo', ['u_code' => $orderInfo['u_code']]);
        $userInfo = $user['result'];

        // 根据bid获取pid
        $saveData = [
            'p_id' => $orderInfo['product_id'],
            'b_id' => $bid,
            'userName' => $userInfo['u_true_name'],
            'idCardNo' => $userInfo['u_ident_no'],
            'u_code' => $orderInfo['u_code'],
            'order_num' => $orderInfo['order_num'],
            'phone' => $userInfo['u_name'],
            'userEmail' => $params['insuranceEmail'],
            'userEducation' => $this->educationMapping($userInfo['u_edu_degree']),
            'userSchool' => $params['insuranceSchool'],
            'startTime' => $params['startTime'],
            'endTime' => $params['endTime'],
            'schoolDay' => $params['schoolDay'],
            'user_course_time' => $params['classHour']
        ];
        Log::write($saveData, '保存用户保险表参数', true, 'insurance/');
        $userInsurance = $this->getWS('credit', 'Insurance@saveInsuranceData', $saveData);
        Log::write($userInsurance, '保存用户保险表结果', true, 'insurance/');
        // 查询是否可以投保
        Log::write($saveData, '预投保保存参数', true, 'insurance/');
        $res = $this->getWS('channel', 'Insurance@preInsurance', $userInsurance['result']);
        Log::write($res, '预投保保存结果', true, 'insurance/');
        //验证是否可以投保
        if($res['status'] == '0000'){
            //投保成功更新预投保状态
            $this->getWS('credit', 'Insurance@updatePreInsuranceStatus', ['reqt_id'=>$userInsurance['result']['reqt_id'],'pre_insurance_status'=>1]);
            session('insurance_save', '1');
        }else{
            $this->getWS('credit', 'Insurance@updatePreInsuranceStatus', ['reqt_id'=>$userInsurance['result']['reqt_id'],'pre_insurance_status'=>2]);
            return $this->parse_data(['code'=>Constant::FAILED_CODE, 'msg'=>$res['result']]);
        }

        return $this->parse_data(['code' => Constant::SUCCESS_CODE, 'msg'=>'请求成功']);
    }

    private function educationMapping($key) {
        $res = 2;
        if (in_array($key, [10])) {
            $res = 5;
        } else if(in_array($key, [20])) {
            $res = 4;
        } else if(in_array($key, [30])) {
            $res = 3;
        }

        return $res;
    }

    /*
     * 我的保单页面
     */
    public function insuranceState(){
        //获取保险信息
        $insuranceInfo = $this->getWS('credit', 'Insurance@getInsuranceInfo', ['u_code'=>$this->uid,'pre_insurance_status'=>1,'warranty_status'=>2,'training_start_time'=>['lt',date('Y-m-d H:i:s',time())],'training_end_time'=>['gt',date('Y-m-d H:i:s',time())],'is_delete'=>2]);

        return view('order/insurance_state',['data'=>$insuranceInfo['result']]);
    }

    /**
     * 保存调查问卷信息
     * @Author   lihuifeng
     */
    public function saveCollection() {
        $request = request();
        $params = $request->param();

        $params['type'] = 10;
        $params['create_date'] = date('Y-m-d H:i:s',time());
        $result = $this->getWS('ucenter', 'users@saveCollection', $params);
        if ($result['status'] != '2000') {
            return $this->parse_data(['code' => 5000, 'msg' => $result['msg']]);
        }

        return $this->parse_data();
    }
}
